/*
 * Copyright (c) 2017 zhangcm. All Rights Reserved.
 */
package com.jnzc.ocr.serv.shop.helper;

import com.jnzc.ocr.common.utils.BusinessUtils;
import com.jnzc.ocr.common.utils.CalculateUtils;
import com.jnzc.ocr.common.utils.ValidateUtils;
import com.jnzc.ocr.serv.shop.consts.ShopOrderConsts;
import com.jnzc.ocr.serv.shop.entity.ShopOrder;
import com.jnzc.ocr.serv.shop.entity.ShopOrderSaleDetail;
import com.jnzc.ocr.serv.shop.entity.ShopRefundSaleDetail;
import com.jnzc.ocr.serv.shop.vo.ShopRefundSaleCreateVo;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;

/**
 * @author zhangcm
 * @version 1.0, 2017/11/26
 */
public class ShopRefundSaleHelper {

    private ShopRefundSaleHelper() {}

    public static void check(ShopOrder order) {
        BusinessUtils.isTrue(order.getType().equals(ShopOrderConsts.TYPE_SALE), "不是销售订单");
        BusinessUtils.isTrue(order.getState().equals(ShopOrderConsts.STATE_FINISH), "订单未完成");
        BusinessUtils.isTrue(null == order.getIfRefund() || !order.getIfRefund(), "订单已退款");
    }

    public static void checkDetail(ShopRefundSaleCreateVo param, Map<Long, ShopOrderSaleDetail> detailMap) {
        ValidateUtils.notEmpty(param.getDetailList(), "详情");
        for (ShopRefundSaleCreateVo.Detail detailParam : param.getDetailList()) {
            ValidateUtils.isId(detailParam.getSkuId(), "产品SKU");
            ValidateUtils.inRange(detailParam.getNum(), 1, "退货数量");
            ShopOrderSaleDetail detail = detailMap.get(detailParam.getSkuId());
            BusinessUtils.notNull(detail, "订单中不存在该商品");
            Integer canRefundNum = CalculateUtils.sub(detail.getNum(), detail.getRefundNum());
            BusinessUtils.isTrue(canRefundNum >= detailParam.getNum(), "退货数量必须小于可退数量");
        }
    }

    public static BigDecimal getRefundAmount(ShopOrderSaleDetail detail, Integer refundNum) {
        BigDecimal amount = CalculateUtils.sub(detail.getSaleAmount(), detail.getDiscountAmount());
        BigDecimal remainderAmount = CalculateUtils.div(amount.multiply(new BigDecimal(100)).intValue() % detail.getNum(), 100, 2);
        BigDecimal canDivAmount = CalculateUtils.sub(amount, remainderAmount);
        BigDecimal result = CalculateUtils.div(CalculateUtils.mul(canDivAmount, refundNum), detail.getNum(), 2);
        Integer canRefundNum = CalculateUtils.sub(detail.getNum(), detail.getRefundNum());
        if(canRefundNum == 0) {
            result = CalculateUtils.add(result, remainderAmount);
        }
        return result;
    }

    public static BigDecimal getTotalRefundAmount(List<ShopRefundSaleDetail> list) {
        BigDecimal result = BigDecimal.ZERO;
        for (ShopRefundSaleDetail obj : list) {
            result = CalculateUtils.add(result, obj.getRefundAmount());
        }
        return result;
    }
}
